﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xinchen.DbUtils;
using Xinchen.SOA.Manager.Api.Contracts;
using Xinchen.Utils;

namespace Xinchen.SOA.Client
{
    public class ServiceHostingClient : Singleton<ServiceHostingClient>
    {
        IServiceHostingService BuildService()
        {
            var _service = ServiceBuilder.BuildService<IServiceHostingService>(ServiceConsts.ServiceUrl, ServiceConsts.ServiceHostingServiceName);
            return _service;
        }

        public PageResult<ServiceHostingInfo> GetServiceHostings(int page, int pageSize, IList<SqlFilter> filters)
        {
            return BuildService().GetServiceHostings().Where(filters).Page(page, pageSize);
        }
        public IList<ServiceHostingInfo> GetServiceHostings(int administratorId, IList<SqlFilter> filters)
        {
            return BuildService().GetServiceHostings().ToList();
        }

        public ServiceHostingInfo GetServiceHosting(int id)
        {
            return BuildService().GetServiceHostings().FirstOrDefault(x => x.Id == id);
        }

        public void UpdateServiceHostings(int id, string name, string address)
        {
            var _service = BuildService();
            using (_service as IDisposable)
            {
                var result = _service.UpdateServiceHosting(new UpdateServiceHostingRequest()
                {
                    Address = address,
                    Id = id,
                    Name = name
                });
                if (result.ResultCode != 0)
                {
                    throw new ApplicationException(result.ResultMessage);
                }
            }
        }
        public void AddServiceHosting(AddServiceHostingRequest request)
        {
            var service = BuildService();
            using (service as IDisposable)
            {
                var result = service.AddServiceHosting(request);
                if (result.ResultCode != 0)
                {
                    throw new ApplicationException(result.ResultMessage);
                }
            }
        }
    }
}
